package com.glory.wxelectricitypda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.LotInfoAdapter;
import com.glory.wxelectricitypda.adapter.RelocationAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.EqpEntoty;
import com.glory.wxelectricitypda.bean.LotBean;
import com.glory.wxelectricitypda.bean.MLotBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;

public class RelocationActivity extends BaseDialogActivity {

    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.tvTowareHouseID)
    FreeUI_ClearEditText tvTowareHouseID;
    @BindView(R.id.tvTostorageID)
    FreeUI_ClearEditText tvTostorageID;
    @BindView(R.id.rvRelocationInfoList)
    RecyclerView rvRelocationInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvDelect)
    TextView tvDelect;
    @BindView(R.id.llLotInfo)
    LinearLayout llLotInfo;

    private RelocationAdapter mRelocationAdapter;
    private LotInfoAdapter lotInfoAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_relocation;
    }

    @Override
    protected void initView() {
        rvRelocationInfoList.setLayoutManager(new LinearLayoutManager(RelocationActivity.this));
        rvRelocationInfoList.setItemAnimator(new DefaultItemAnimator());
        rvRelocationInfoList.addItemDecoration(new DividerItemDecoration(RelocationActivity.this, 1));
        mRelocationAdapter = new RelocationAdapter(null);
        mRelocationAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRelocationAdapter.isFirstOnly(true);
        rvRelocationInfoList.setAdapter(mRelocationAdapter);
        tvDelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRelocationAdapter.setNewData(null);
            }
        });
    }

    @Override
    protected void initData() {
        lotInfoAdapter = new LotInfoAdapter(null);
        lotInfoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lotInfoAdapter.isFirstOnly(true);

        initEdit(etLotId, s -> {
            if (s.replace("|",",").split(",").length > 2){
                etLotId.setText(s.replace("|",",").split(",")[2]);
            }

            getData();
        });
    }

    private void submin(String mLotID) {
        if (lotInfoAdapter.getData().size() == 0){
            showToast("暂无扩散批信息",false);
            return;
        }

        boolean isAdd = true;
        for (EqpEntoty.MaterierlBean datum : mRelocationAdapter.getData()) {
            if (datum.getmLotId().equals(mLotID)) {
                isAdd = false;
            }
        }
        if (!isAdd) {
            showToast("当前物料批已转移", false);
            etLotId.setText("");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    etLotId.requestFocus();
                }
            }, 500);
            return;
        }
        if (tvTowareHouseID.getText().toString().equals("")) {
            showToast("请输入转移后仓库", false);
            return;
        }
        if (tvTostorageID.getText().toString().equals("")) {
            showToast("请输入转移后位置号", false);
            return;
        }
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("TOWAREHOUSEID", tvTowareHouseID.getText().toString().trim());
            map.put("TOSTORAGEID", tvTostorageID.getText().toString().trim());
            map.put("TOSTORAGETYPE", "receive");
            map.put("ACTIONCODE", "A");
            ArrayList<MLotBean> lotBeans = new ArrayList<>();
            MLotBean mLotBean = new MLotBean();
            mLotBean.setMLOTID(mLotID);
            lotBeans.add(mLotBean);
            JSONArray jsonArray = new JSONArray(new Gson().toJson(lotBeans));
            map.put("MLOTLIST", jsonArray);
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitTransferMLot");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty.MKittingBean>>(
                new TypeToken<ResponseBean<EqpEntoty.MKittingBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<EqpEntoty.MKittingBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("转移成功", true);
                    mRelocationAdapter.addData(0, response.body().getBody().getMLOTLIST());
                    mRelocationAdapter.notifyDataSetChanged();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            etLotId.setText("");
                            etLotId.requestFocus();
                        }
                    }, 500);
                }
            }

            @Override
            public void onError(Response<ResponseBean<EqpEntoty.MKittingBean>> response) {
                super.onError(response);
                loadError(response.getException(), "EUIT.EuitTransferMLot");
            }
        });
    }

    private void createDialog() {
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(RelocationActivity.this).inflate(R.layout.dialog_lot_info, null);
        RecyclerView rvLotInfoList = view.findViewById(R.id.rvLotInfoList);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        rvLotInfoList.setLayoutManager(new LinearLayoutManager(RelocationActivity.this));
        rvLotInfoList.setItemAnimator(new DefaultItemAnimator());
        rvLotInfoList.addItemDecoration(new DividerItemDecoration(RelocationActivity.this, 1));
        rvLotInfoList.setAdapter(lotInfoAdapter);
        lotInfoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                submin(lotInfoAdapter.getData().get(i).getmLotId());
                freeU_generalFragmentDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                freeU_generalFragmentDialog.dismiss();
            }
        });

        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(getSupportFragmentManager(),"DIALOG");
    }

    private void getData() {
        if (tvTowareHouseID.getText().toString().equals("")) {
            showToast("请输入转移后仓库", false);
            return;
        }
        if (tvTostorageID.getText().toString().equals("")) {
            showToast("请输入转移后位置号", false);
            return;
        }
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("TOWAREHOUSEID", tvTowareHouseID.getText().toString().trim());
            map.put("TOSTORAGEID", tvTostorageID.getText().toString().trim());
            map.put("TOSTORAGETYPE", "receive");
            map.put("ACTIONCODE", "Q");
            ArrayList<MLotBean> lotBeans = new ArrayList<>();
            MLotBean mLotBean = new MLotBean();
            mLotBean.setMLOTID(etLotId.getText().toString());
            lotBeans.add(mLotBean);
            JSONArray jsonArray = new JSONArray(new Gson().toJson(lotBeans));
            map.put("MLOTLIST", jsonArray);
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitTransferMLot");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<EqpEntoty.MKittingBean>>(
                new TypeToken<ResponseBean<EqpEntoty.MKittingBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<EqpEntoty.MKittingBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (EqpEntoty.MaterierlBean datum : mRelocationAdapter.getData()) {
                        for (int i = response.body().getBody().getMLOTLIST().size()-1; i >= 0; i--) {
                            if (datum.getmLotId().equals(response.body().getBody().getMLOTLIST().get(i).getmLotId())){
                                response.body().getBody().getMLOTLIST().remove(i);
                            }
                        }
                    }
                    lotInfoAdapter.setNewData(response.body().getBody().getMLOTLIST());

                    createDialog();
                }
            }

            @Override
            public void onError(Response<ResponseBean<EqpEntoty.MKittingBean>> response) {
                super.onError(response);
                loadError(response.getException(), "EUIT.EuitTransferMLot");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("移动货架");
        return new FreeUI_AddViewEntity("header", llMain);
    }
}

